/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ie.tcd.cs.railtickets.server.dao.impl;

import ie.tcd.cs.railtickets.server.dao.RouteStationDAO;
import ie.tcd.cs.railtickets.server.domain.PathTime;
import ie.tcd.cs.railtickets.server.domain.Route;
import ie.tcd.cs.railtickets.server.domain.RouteStation;
import java.util.List;
import static ie.tcd.cs.railtickets.server.dao.impl.HibernateSessionFactory.getSession;

/**
 *
 * @author Wenbo Sun
 */
public class RouteStationDAOImpl extends AbstractBaseDAOImpl implements RouteStationDAO{

    public List<Long> findIdsByStation(String station) {
        String query = "select routeStation.id from RouteStation routeStation" +
                "where routeStation.name = ?";
        List list = getSession().createQuery(query).setParameter(0, station).list();
        return list;
    }

    public int[] getSequencesByTime(PathTime pathTime) {
        String query = "select travelTime.path.source.sequenceNum, travelTime.path.destination.sequenceNum from PathTime travelTime " +
                "where travelTime = ?";
        Object o = getSession().createQuery(query).setParameter(0, pathTime).iterate().next();
        int[] results = new int[2];
        Object os[] = (Object[])o;
        results[0] = (Integer)os[0];
        results[1] = (Integer)os[1];
        return results;
    }

    public List findByPathTime(PathTime pathTime) {
        String query = "select travelPath.source, travelPath.destination from TimeTable travelTime, travelTime.path travelPath " +
                "where travelTime = ?";
        List list = getSession().createQuery(query).setParameter(0, pathTime).list();
        return list;
    }

    public RouteStation findBy(Route route, int sequence) {
        String query = "from RouteStation routeStation where routeStation.route = ? and routeStation.sequenceNum = ?";
        RouteStation result = (RouteStation)getSession().createQuery(query).setParameter(0, route)
                .setParameter(1, sequence).uniqueResult();
        return result;
    }

    public List<RouteStation> findBy(Route route, int... sequences) {
        String query = "from RouteStation routeStation where routeStation.route = ? and "
                + "routeStation.sequenceNum >= ? and routeStation.sequenceNum < ? order by routeStation.sequenceNum";
        List result = getSession().createQuery(query).setParameter(0, route)
                .setParameter(1, sequences[0]).setParameter(2, sequences[1]).list();
        return result;
    }


}
